import sys
import pygame

from Alien import Alien
from Bullet import Bullet


def check_events(gameSetting, screen, ship, bullets):
    """
    响应按键和鼠标事件
    :return:
    """
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:  # 按下键盘
            check_keydown_events(event, gameSetting, screen, ship, bullets)
        elif event.type == pygame.KEYUP:  # 松开按键
            check_keyup_events(event, ship)


def check_keydown_events(event, gameSetting, screen, ship, bullets):
    """
    捕捉按下键盘事件
    """

    # 上下左右键控制飞船
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    if event.key == pygame.K_LEFT:
        ship.moving_left = True
    if event.key == pygame.K_UP:
        ship.moving_up = True
    if event.key == pygame.K_DOWN:
        ship.moving_down = True

    # 空格键发射子弹
    if event.key == pygame.K_SPACE:
        fire_bullet(screen, gameSetting, ship, bullets)

    if event.key == pygame.K_q:
        sys.exit()


def check_keyup_events(event, ship):
    """
    捕捉松开键盘事件
    """

    # 上下左右键控制飞船
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    if event.key == pygame.K_LEFT:
        ship.moving_left = False
    if event.key == pygame.K_UP:
        ship.moving_up = False
    if event.key == pygame.K_DOWN:
        ship.moving_down = False


def update_screen(gameSetting, screen, ship, bullets, aliens):
    """
    绘制一个空屏幕，并擦去旧屏幕
    :param gameSetting:
    :param screen:
    :param ship:
    :return:
    """
    screen.fill(gameSetting.bg_color)  # 填充颜色
    ship.blitShip()  # 绘制飞船
    aliens.draw(screen)  # 绘制外星飞船
    # 绘制子弹
    for bullet in bullets.sprites():
        bullet.drawBullet()

    pygame.display.flip()  # 让最近绘制的屏幕可见


def fire_bullet(screen, gameSetting, ship, bullets):
    """
    发射子弹
    """
    if len(bullets) < gameSetting.bullets_allowed:
        # 创建一颗子弹，并将其加入到编组bullets中
        newBullet = Bullet(gameSetting, screen, ship)
        bullets.add(newBullet)


def update_bullets(gameSetting, screen, ship, bullets, aliens):
    """
    更新子弹，检测是否击中
    """
    bullets.update()
    for bullet in bullets:
        if bullet.rect.top <= 0:
            bullets.remove(bullet)  # 删除消失在屏幕之外的子弹

    check_bullet_alien_collisions(gameSetting, screen, ship, aliens, bullets)


def check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets):
    """响应子弹和外星人的碰撞"""
    # 删除发生碰撞的子弹和外星人
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
    if len(aliens) == 0:
        # 删除现有的所有子弹，并创建一个新的外星人群
        bullets.empty()
        create_fleet(ai_settings, screen, ship, aliens)


def get_number_aliens_x(ai_settings, alien_width):
    """计算每行可容纳多少个外星飞船"""
    available_space_x = ai_settings.screen_width - 2 * alien_width
    number_aliens_x = int(available_space_x / (2 * alien_width))
    return number_aliens_x


def get_number_rows(ai_settings, ship_height, alien_height):
    """计算屏幕可容纳多少行外星飞船"""
    # 外星飞船间距为外星飞船宽度
    available_space_y = (ai_settings.screen_height - (5 * alien_height) - ship_height)
    number_rows = int(available_space_y / (2 * alien_height))
    return number_rows


def create_alien(ai_settings, screen, aliens, column_number, row_number, column_numbers):
    """创建一个外星飞船并将其放在当前行"""
    alien = Alien(ai_settings, screen)
    alien_width = alien.rect.width

    # 注释的代码不能实现外星飞船居中
    # alien.x = alien_width + 2 * alien_width * column_number
    # alien.rect.x = alien.x

    # 以下代码实现了外星飞船居中显示
    # 计算第一个外星飞船的横向位置
    # [屏幕宽 - 所有飞船占的宽度 - 飞船之间空白的宽度]/2   即为 左右两边的边距，也就是第一个外星飞船的横向坐标
    # [屏幕宽 - 一个外星飞船宽度*数量 - 一个外星飞船宽度 * （数量 - 1）]/2
    firstAlienX = int(
        (ai_settings.screen_width - column_numbers * alien_width - (column_numbers - 1) * alien_width) / 2)
    alien.x = firstAlienX + 2 * alien_width * column_number
    alien.rect.x = alien.x

    alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
    aliens.add(alien)


def create_fleet(ai_settings, screen, ship, aliens):
    """创建外星飞船群"""
    # 创建一个外星飞船，并计算一行可容纳多少个外星飞船
    alien = Alien(ai_settings, screen)

    # 每行的外星飞船数量
    column_numbers = get_number_aliens_x(ai_settings, alien.rect.width)
    # 外星飞船行数
    number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height)

    # 创建第一行外星飞船
    for row_number in range(number_rows):
        for column_number in range(column_numbers):
            create_alien(ai_settings, screen, aliens, column_number, row_number, column_numbers)


def update_aliens(ai_settings, ship, aliens):
    """ 检查是否有外星飞船到达屏幕边缘 然后更新所有外星飞船的位置 """
    check_fleet_edges(ai_settings, aliens)
    aliens.update()
    # 检测外星人和飞船之间的碰撞
    if pygame.sprite.spritecollideany(ship, aliens):
        print("Ship hit!!!")

def check_fleet_edges(ai_settings, aliens):
    """有外星飞船到达边缘时采取相应的措施"""
    for alien in aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(ai_settings, aliens)
            break


def change_fleet_direction(ai_settings, aliens):
    """将整群外星飞船下移，并改变它们的方向"""
    for alien in aliens.sprites():
        alien.rect.y += ai_settings.fleet_drop_speed
    ai_settings.fleet_direction *= -1



